package com.yc.web.controller;

import com.yc.DTO.TestAnswerDTO;
import com.yc.services.TestService;
import com.yc.utils.JwtUtil;
import com.yc.web.controller.model.ResponseResult;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 心理测评控制器
 */
@RestController
@RequestMapping("/api/test")
@Slf4j
@CrossOrigin
public class TestController {

    @Autowired
    private TestService testService;


    /**
     * 获取测评分类列表
     */
    @GetMapping("/categories")
    public ResponseResult getCategories() {
        try {
            return testService.getCategories();
        } catch (Exception e) {
            log.error("获取测评分类失败", e);
            return ResponseResult.error("获取测评分类失败");
        }
    }

    /**
     * 获取测评列表
     */
    @GetMapping("/list")
    public ResponseResult getTestList(
            @RequestParam(required = false) String categoryId,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam("userId") Long userId) {
        
        try {
            return testService.getTestList(userId, categoryId, status, page, size);
        } catch (Exception e) {
            log.error("获取测评列表失败", e);
            return ResponseResult.error("获取测评列表失败");
        }
    }

    /**
     * 获取测评详情
     */
    @GetMapping("/{testId}")
    public ResponseResult getTestDetail(
            @PathVariable Long testId,
            @RequestParam("userId") Long userId) {
        
        try {
            // 校验参数
            if (testId == null || testId <= 0) {
                return ResponseResult.error("测评ID不能为空");
            }
            
//            Long userId = null;
            
            return testService.getTestDetail(testId, userId);
        } catch (Exception e) {
            log.error("获取测评详情失败", e);
            return ResponseResult.error("获取测评详情失败");
        }
    }

    /**
     * 开始测评
     */
    @PostMapping("/{testId}/start")
    public ResponseResult startTest(
            @PathVariable Long testId,
            @RequestParam(value="userId") Long userId) {
        
        try {
            // 1. 校验参数
            if (testId == null || testId <= 0) {
                return ResponseResult.error("测评ID不能为空");
            }
            return testService.startTest(testId, userId);
        } catch (Exception e) {
            log.error("开始测评失败", e);
            return ResponseResult.error("开始测评失败");
        }
    }

    /**
     * 保存答题进度
     */
    @PostMapping("/progress")
    public ResponseResult saveProgress(
            @RequestBody TestAnswerDTO answerDTO,
            @RequestParam("userId") Long userId) {
        
        try {
            // 1. 校验参数
            if (answerDTO == null) {
                return ResponseResult.error("答题数据不能为空");
            }
            
            answerDTO.setUserId(userId);
            return testService.saveProgress(answerDTO);
        } catch (Exception e) {
            log.error("保存答题进度失败", e);
            return ResponseResult.error("保存答题进度失败");
        }
    }

    /**
     * 提交测评
     */
    @PostMapping("/submit")
    public ResponseResult submitTest(
            @RequestBody TestAnswerDTO answerDTO,
            @RequestParam("userId") Long userId) {
        
        try {
            // 1. 校验参数
            if (answerDTO == null) {
                return ResponseResult.error("答题数据不能为空");
            }

            // Long userId = userService.getUserIdByUsername(username);
            
            answerDTO.setUserId(userId);
            return testService.submitTest(answerDTO);
        } catch (Exception e) {
            log.error("提交测评失败", e);
            return ResponseResult.error("提交测评失败");
        }
    }

    /**
     * 获取测评结果
     */
    @GetMapping("/result/{recordId}")
    public ResponseResult getTestResult(
            @PathVariable Long recordId,
            @RequestParam("userId") Long userId) {
        
        try {
            // 1. 校验参数
            if (recordId == null || recordId <= 0) {
                return ResponseResult.error("记录ID不能为空");
            }
            // Long userId = userService.getUserIdByUsername(username);
            
            return testService.getTestResult(recordId, userId);
        } catch (Exception e) {
            log.error("获取测评结果失败", e);
            return ResponseResult.error("获取测评结果失败");
        }
    }

    /**
     * 获取历史测评记录
     */
    @GetMapping("/history")
    public ResponseResult getTestHistory(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam("userId") Long userId) {
        
        try {
            
            return testService.getTestHistory(userId, page, size);
        } catch (Exception e) {
            log.error("获取历史测评记录失败", e);
            return ResponseResult.error("获取历史测评记录失败");
        }
    }

    /**
     * 重新测评
     */
    @PostMapping("/{testId}/retake")
    public ResponseResult retakeTest(
            @PathVariable Long testId,
            @RequestParam("userId") Long userId) {
        
        try {
            // 1. 校验参数
            if (testId == null || testId <= 0) {
                return ResponseResult.error("测评ID不能为空");
            }
            
            return testService.retakeTest(testId, userId);
        } catch (Exception e) {
            log.error("重新测评失败", e);
            return ResponseResult.error("重新测评失败");
        }
    }

    /**
     * 分享测评结果
     */
    @PostMapping("/share/{recordId}")
    public ResponseResult shareResult(
            @PathVariable Long recordId,
            @RequestParam("userId") Long userId) {
        
        try {
            // 1. 校验参数
            if (recordId == null || recordId <= 0) {
                return ResponseResult.error("记录ID不能为空");
            }
            
            return testService.shareResult(recordId, userId);
        } catch (Exception e) {
            log.error("分享测评结果失败", e);
            return ResponseResult.error("分享测评结果失败");
        }
    }

    /**
     * 获取用户测评统计
     */
    @GetMapping("/stats")
    public ResponseResult getUserTestStats(@RequestParam("userId") Long userId) {
        try {
            
            return testService.getUserTestStats(userId);
        } catch (Exception e) {
            log.error("获取用户测评统计失败", e);
            return ResponseResult.error("获取用户测评统计失败");
        }
    }

    /**
     * 获取公开的测评结果（用于分享）
     */
    @GetMapping("/share/result/{shareToken}")
    public ResponseResult getSharedResult(@PathVariable String shareToken) {
        try {
            // 1. 校验参数
            if (shareToken == null || shareToken.trim().isEmpty()) {
                return ResponseResult.error("分享链接无效");
            }
            
            return testService.getSharedResult(shareToken);
        } catch (Exception e) {
            log.error("获取分享结果失败", e);
            return ResponseResult.error("获取分享结果失败");
        }
    }
} 